package com.itheima.servlet;

import com.itheima.bean.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/userLogin")
public class UserLogin extends HttpServlet {
    //用户登录
    private final UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.selectUser(username, password);
        if(user==null){
            //用户为空登录失败使用转发跳回注册页面  并在上方显示登录失败的信息
            req.setAttribute("errorMessage","用户名或密码错误");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }else {
            String remember = req.getParameter("remember");
            if (remember!=null) {
                //如果用户勾选了记住我创建cookie记录用户密码和用户名   有效期为30天
                Cookie cookieUserName = new Cookie("username", username);
                cookieUserName.setMaxAge(60*60*24*30);
                Cookie cookiePassword = new Cookie("password", password);
                cookiePassword.setMaxAge(60*60*24*30);
                resp.addCookie(cookieUserName);
                resp.addCookie(cookiePassword);
            }
            //登录成功条状到登录成功的页面
            //resp.sendRedirect("brand.jsp");
            //登录成功跳转到投票页面
            resp.sendRedirect("vote.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
